#import "AliAuthPlugin.h"
#import <AlipaySDK/AlipaySDK.h>

@implementation AliAuthPlugin
FlutterMethodChannel* channel;
+ (void)registerWithRegistrar:(NSObject<FlutterPluginRegistrar>*)registrar {
  channel = [FlutterMethodChannel
      methodChannelWithName:@"ali_auth"
            binaryMessenger:[registrar messenger]];
  AliAuthPlugin* instance = [[AliAuthPlugin alloc] init];
  [registrar addMethodCallDelegate:instance channel:channel];
}

- (void)handleMethodCall:(FlutterMethodCall*)call result:(FlutterResult)result {
    NSString* methodName = call.method;
  if ([@"getPlatformVersion" isEqualToString:methodName]) {
    result([@"iOS " stringByAppendingString:[[UIDevice currentDevice] systemVersion]]);
  } else if([@"toAuth" isEqualToString:methodName]) {
      NSString* arguments = call.arguments;
      [self toAuth: arguments result: result];
  } else {
    result(FlutterMethodNotImplemented);
  }
}
- (BOOL)application:(UIApplication*)application
          openURL:(NSURL*)url
sourceApplication:(NSString*)sourceApplication
       annotation:(id)annotation 
{
    if ([url.host isEqualToString:@"safepay"]) {
        // 支付跳转支付宝钱包进行支付，处理支付结果
        [[AlipaySDK defaultService] processOrderWithPaymentResult:url standbyCallback:^(NSDictionary *resultDic) {
            NSLog(@"result = %@",resultDic);
        }];
        
        // 授权跳转支付宝钱包进行支付，处理支付结果
        [[AlipaySDK defaultService] processAuth_V2Result:url standbyCallback:^(NSDictionary *resultDic) {
            NSLog(@"result = %@",resultDic);
            // 解析 auth code
            NSString *result = resultDic[@"result"];
            NSString *authCode = nil;
            if (result.length>0) {
                NSArray *resultArr = [result componentsSeparatedByString:@"&"];
                for (NSString *subResult in resultArr) {
                    if (subResult.length > 10 && [subResult hasPrefix:@"auth_code="]) {
                        authCode = [subResult substringFromIndex:10];
                        break;
                    }
                }
            }
            NSLog(@"授权结果 authCode = %@", authCode?:@"");
        }];
    }
    return YES;
}

// NOTE: 9.0以后使用新API接口
- (BOOL)application:(UIApplication*)application
openURL:(NSURL*)url
options:(NSDictionary<UIApplicationOpenURLOptionsKey, id>*)options
{
    if ([url.host isEqualToString:@"safepay"]) {
        // 支付跳转支付宝钱包进行支付，处理支付结果
        [[AlipaySDK defaultService] processOrderWithPaymentResult:url standbyCallback:^(NSDictionary *resultDic) {
            NSLog(@"result = %@",resultDic);
        }];
        
        // 授权跳转支付宝钱包进行支付，处理支付结果
        [[AlipaySDK defaultService] processAuth_V2Result:url standbyCallback:^(NSDictionary *resultDic) {
            NSLog(@"result = %@",resultDic);
            // 解析 auth code
            NSString *result = resultDic[@"result"];
            NSString *authCode = nil;
            if (result.length>0) {
                NSArray *resultArr = [result componentsSeparatedByString:@"&"];
                for (NSString *subResult in resultArr) {
                    if (subResult.length > 10 && [subResult hasPrefix:@"auth_code="]) {
                        authCode = [subResult substringFromIndex:10];
                        break;
                    }
                }
            }
            NSLog(@"授权结果 authCode = %@", authCode?:@"");
        }];
    }
    return YES;
}

- (void)toAuth:(NSString*)arguments result:(FlutterResult) result {
    [[AlipaySDK defaultService] auth_V2WithInfo:arguments
    fromScheme:@"ali_auth"
      callback:^(NSDictionary *resultDic) {
          NSLog(@"result = %@",resultDic);
          // 解析 auth code
          NSString *result = resultDic[@"result"];
          NSString *authCode = nil;
        [channel invokeMethod:@"authCallBack" arguments:resultDic];
          if (result.length>0) {
              NSArray *resultArr = [result componentsSeparatedByString:@"&"];
              for (NSString *subResult in resultArr) {
                  if (subResult.length > 10 && [subResult hasPrefix:@"auth_code="]) {
                      authCode = [subResult substringFromIndex:10];
                      break;
                  }
              }
          }
          NSLog(@"授权结果 authCode = %@", authCode?:@"");
      }];
}

@end
